import 'package:fluwx/fluwx.dart';
import 'package:honeypotflutter/net/public_http.dart';
import 'package:honeypotflutter/public/public_total.dart';
import 'package:honeypotflutter/publicBussine/view/bussine_modal.dart';
import 'bussine_wechat_model.dart';

/// 微信支付

class MGWechat {
  static final Fluwx fluwx = Fluwx();
  static String appID = "wxf7c0b479d76f70fc";

  /*
  * 注册
  * */
  static registerApi() async {
    fluwx.registerApi(appId: appID, universalLink: appID);
  }

  /*
  * 开始支付
  * */
  static Future<bool> startWechatPay(double price) async {
    if (await fluwx.isWeChatInstalled) {
      HLTotal.total("请安装微信完成支付");
      return Future.error("请安装微信完成支付");
    }
    Map<String, dynamic> param = {"TotalFee": price};
    try {
      Map<String, String> result = await MGHttp.get(
        "services/app/WeixinPay/GetWeixinPrepayIdAsync",
        params: param,
        progress: "支付中...",
      );
      WechatModel model = WechatModel.fromJson(result);
      var cancelable;
      cancelable = fluwx.addSubscriber((res) {
        if (res.errCode == 0) {
          /// 支付成功
          cancelable.cancel();
        }
      });
      await _pay(model);
      return true;
    } catch (error) {
      MGModal.totalError(error);
      return Future.error(error);
    }
  }

  /*
  * 支付
  * */
  static Future<bool> _pay(WechatModel model) async {
    try {
      await fluwx.pay(
          which: Payment(
        appId: appID,
        partnerId: model.prepayId!,
        prepayId: model.prepayId!,
        packageValue: "Sign=WXPay",
        nonceStr: model.nonceStr!,
        timestamp: model.timestamp!,
        sign: model.paySign!,
      ));
      return true;
    } catch (error) {
      MGModal.totalError(error);
      return Future.error(error);
    }
  }
}
